<template>
  <div class="cart">
    <!-- 购物车标题 -->
    <p class="title"><i class="el-icon-shopping-cart-2"></i>购物车</p>
    <!-- 购物车列表 -->
    <div class="cart-list">
      <div
        v-for="(item, index) in cartList"
        :key="index"
        class="record"
        v-show="item.status == 0"
      >
        <el-checkbox
          class="checkBox"
          v-model="checkedCart[index].checked"
          @change="handleCheckedCartChange"
        ></el-checkbox>
        <img :src="item.imgAddress" alt="" />
        <p class="name">《{{ item.name }}》</p>
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;座位：<span
          v-for="(item2, index2) in item.seats"
          :key="index2"
          >{{ item2.line }}排{{ item2.row }}座
        </span>

        <p>手机号码：{{ item.tel }}</p>
        <p class="time">
          开场时间：<span>{{ item.start }}</span>
        </p>
        <el-button
          type="danger"
          icon="el-icon-delete"
          class="btn"
          @click="handleDelete(item.id)"
          circle
          >删除</el-button
        >
        <!-- <el-link type="danger"  ></el-link> -->
        <p class="price">￥{{ item.price }}</p>
      </div>
    </div>
    <!-- 结算框 -->
    <div class="settlement">
      <el-checkbox
        @change="handleCheckAllChange"
        v-model="checkAll"
        class="checkAll"
        ><span>全选</span></el-checkbox
      >
      <el-button type="danger" class="payBtn" @click="payBtn()"
        >全部结算</el-button
      >
      <p>合计：￥{{ sum }}</p>
    </div>
    <!-- 结算按钮对话框 -->
    <el-dialog
      :visible.sync="dialogVisible1"
      width="30%"
      class="dialog1"
      center
    >
      <p class="title"><i class="el-icon-circle-check">提示</i></p>
      <span class="text">请您仔细确认订单金额为{{ sum }}元，是否继续？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible1 = false">取消支付</el-button>
        <el-button type="primary" @click="confirmPayment()">确认支付</el-button>
      </span>
    </el-dialog>

    <!-- 二维码 -->
    <el-dialog :visible.sync="dialogVisible2" width="350px" class="dialog2">
      <span class="text">扫码支付</span>
      <div id="qrcode"></div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="paySuccess()">支付成功</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { myCart, zfb } from "@/api/cart";
import { addToOrder } from "@/api/order";
import QRCode from "qrcodejs2";
import axios from "axios";
export default {
  data() {
    return {
      dialogVisible1: false,
      dialogVisible2: false,
      centerDialogVisible: true,
      cartList: [
        // {
        //   name: "XXXXX",
        //   line: 3,
        //   row: 2,
        //   tel: "12345678912",
        //   start: "2022-01-20 14:25",
        //   price: 30.5,
        //   imgAddress: require("@/assets/movie/u2282.svg"),
        // },
        // {
        //   name: "XXXXX",
        //   line: 3,
        //   row: 3,
        //   tel: "12345678912",
        //   start: "2022-01-20 14:25",
        //   price: 30.5,
        //   imgAddress: require("@/assets/movie/u2282.svg"),
        // },
        // {
        //   name: "XXXXX",
        //   line: 3,
        //   row: 3,
        //   tel: "12345678912",
        //   start: "2022-01-20 14:25",
        //   price: 30.5,
        //   imgAddress: require("@/assets/movie/u2282.svg"),
        // },
        // {
        //   name: "XXXXX",
        //   line: 3,
        //   row: 3,
        //   tel: "12345678912",
        //   start: "2022-01-20 14:25",
        //   price: 30.5,
        //   imgAddress: require("@/assets/movie/u2282.svg"),
        // },
        // {
        //   name: "XXXXX",
        //   line: 3,
        //   row: 3,
        //   tel: "12345678912",
        //   start: "2022-01-20 14:25",
        //   price: 30.5,
        //   imgAddress: require("@/assets/movie/u2282.svg"),
        // },
        // {
        //   name: "XXXXX",
        //   line: 3,
        //   row: 3,
        //   tel: "12345678912",
        //   start: "2022-01-20 14:25",
        //   price: 30.5,
        //   imgAddress: require("@/assets/movie/u2282.svg"),
        // },
      ],
      checkAll: false,
      checkedCart: [
        // checked:,
        // cart:Object cartList,
        // status:,
      ],
      checkedIds: [],
      sum: 0,
    };
  },
  created() {
    this.loadCarts();
    // console.log(this.checkedCart)
    // if(localStorage.getItem("pay")){
    //   this.paySuccess()
    // }
  },
  methods: {
    // 查询购物车数据后台接口
    loadCarts() {
      myCart(localStorage.getItem("uid")).then((res) => {
        if (res.code == 200) {
          for (let i = 0; i < res.data.length; i++) {
            res.data[i].start = this.formatDate(res.data[i].start);
          }
          // console.log(res)
          this.cartList = res.data;
        }
        // console.log(this.cartList);

        // 选择状态封装
        this.checkedCart = this.cartList.map((item) => {
          return {
            checked: false,
            cart: Object.assign({}, item),
            // status: 0,
          };
        });
      });
    },
    // 删除按钮
    handleDelete(id) {
      this.cartList.splice(index, 1);
      // this.$confirm("确定要删除这条记录吗?", "提示", {
      //   confirmButtonText: "确定",
      //   cancelButtonText: "取消",
      //   type: "warning",
      // })
      //   .then(() => {
      //     delRecord(id).then((res) => {
      //       if (res.code == 200) {
      //         console.log(res)
      //         this.$message({
      //           type: "success",
      //           message: "删除成功!",
      //         });
      //       }
      //     });
      //     this.loadCarts();
      //   })
      //   .catch(() => {
      //     this.$message({
      //       type: "info",
      //       message: "已取消删除",
      //     });
      //   });

      this.loadCarts();
    },
    // 复选框change事件
    handleCheckedCartChange() {
      this.checkOut();
      // console.log(this.checkAll);
    },
    // 复选框全选change事件
    handleCheckAllChange() {
      // debugger;
      if (this.checkAll) {
        this.changeAllChecked(true);
        this.checkOut();
      } else {
        this.changeAllChecked(false);
        this.sum = 0;
        this.checkedIds = [];
      }
    },
    // 传checkbox是否选中的状态
    changeAllChecked(status) {
      for (var i = 0; i < this.checkedCart.length; i++) {
        this.checkedCart[i].checked = status;
      }
    },
    // 封装选择购物车方法
    checkOut() {
      this.sum = 0;
      var isCheckAll = 1; //判断是否全选
      this.checkedIds = [];
      for (var i = 0; i < this.checkedCart.length; i++) {
        if (this.checkedCart[i].checked) {
          this.sum += this.checkedCart[i].cart.price;
          this.checkedIds.push(this.checkedCart[i].cart.id);
          // console.log(this.checkedIds)
          // console.log(this.checkedCart)
        } else {
          isCheckAll = 0;
        }
        // if (!this.checkedCart[i].checked) {
        //   this.checkAll = false;
        // }
      }
      // 1全选 0没有全选
      if (isCheckAll == 1) {
        this.checkAll = true;
      } else {
        this.checkAll = false;
      }
    },
    // 封装已选方法
    select() {
      var result = this.checkedCart.filter((item) => {
        return item.checked;
      });
      return result;
    },
    // 结算按钮
    payBtn() {
      var result = this.select();
      if (result.length == 0) {
        this.$confirm("您还没有选择要支付的订单", "提示", {
          showCancelButton: false,
          confirmButtonText: "确定",
          type: "warning",
          center: true,
        });
      } else {
        this.dialogVisible1 = true;
      }
    },
    confirmPayment() {
      this.dialogVisible1 = false;
      // this.dialogVisible2 = true;
      // setTimeout(function(){
      //   var qrcode = new QRCode(document.getElementById("qrcode"), {
      //   width: 300,
      //   height: 300,
      //   text: "支付",
      //   correctLevel: 1,
      //   background: "#FFFFFF",
      //   foregroud: "#000000",
      // });
      // },100)
      // let data = {
      //   out_trade_no: Math.floor(Math.random() * 999 + 1),
      //   subject: localStorage.getItem("uid") + "dianyingpiao",
      //   total_amount: this.sum,
      // };
      // zfb(data).then((res) => {
      //   console.log(res)
      //   const divForm = document.getElementsByTagName("div");
      //   if (divForm.length) {
      //     document.body.removeChild(divForm[0]);
      //   }
      //   const div = document.createElement("div");
      //   div.innerHTML = res.data; // data就是接口返回的form 表单字符串
      //   document.body.appendChild(div);
      //   document.forms[0].setAttribute("target", "_blank"); // 新开窗口跳转
      //   document.forms[0].submit();
      // });
      let out_trade_no = Math.floor(Math.random() * 999 + 1) + "";
      let subject = localStorage.getItem("uid") + "";
      let total_amount = this.sum + "";
      console.log(out_trade_no);
      console.log(subject);
      console.log(total_amount);
      axios
        .post(
          "http://localhost:8888/pay/pay?out_trade_no=" +
            // "prod001" +
            // Math.floor(Math.random() * 999 + 1).toString() +
            out_trade_no +
            "&subject=" +
            "电影票" +
            subject +
            // localStorage.getItem("uid").toString() +
            "&total_amount=" +
            this.sum.toString()
          // total_amount
        )
        .then((resp) => {
          const divForm = document.getElementsByTagName("div");
          if (divForm.length) {
            document.body.removeChild(divForm[0]);
          }
          const div = document.createElement("div");
          div.innerHTML = resp.data; // data就是接口返回的form 表单字符串
          document.body.appendChild(div);
          // document.forms[0].setAttribute("target", "_blank"); // 新开窗口跳转
          document.forms[0].submit();
          localStorage.setItem("pay",true)
          localStorage.setItem("ids",this.checkedIds)
        });
        setTimeout(() => {
          this.paySuccess()
        }, 1000);
    },
    // 结算成功
    paySuccess() {
      
      let data = {
        ids: this.checkedIds
      };
      console.log(data)
      addToOrder(data).then((res) => {
        console.log(res);
      });
      // this.dialogVisible2 = false;
      localStorage.removeItem("pay");
      localStorage.removeItem("ids");
      // window.location.reload();
    },

    // 日期格式化
    formatDate(dateint) {
      var date = new Date(parseInt(dateint));
      var str = date.getFullYear() + "-";
      if (date.getMonth() < 10) {
        str += "0";
      }
      str += date.getMonth() + 1 + "-";
      if (date.getDate() < 10) {
        str += "0";
      }
      str += date.getDate() + " ";
      if (date.getHours() < 10) {
        str += "0";
      }
      str += date.getHours() + ":";
      if (date.getMinutes() < 10) {
        str += "0";
      }
      str += date.getMinutes() + ":";
      if (date.getSeconds() < 10) {
        str += "0";
      }
      str += date.getSeconds();
      return str;
    },
  },
};
</script>
<style lang="scss" scoped>
.cart {
  position: relative;
  width: 800px;
  height: 820px;
  margin: 40px 0 0 60px;

  .title {
    font-size: 30px;
  }
  .cart-list {
    max-height: 770px;
    overflow: auto;
    .record {
      width: 750px;
      // height: 103px;
      border: 1px lightgray solid;
      padding: 15px;
      margin: 10px 0;
      box-shadow: 1px 1px 2px 0 darkgray;
      position: relative;
      .checkBox {
        float: left;
        margin-top: 40px;
        margin-right: 20px;
      }
      img {
        width: 100px;
        height: 120px;
        float: left;
      }
      p {
        font-size: 12px;
        color: gray;
        margin: 10px 0;
        margin-left: 160px;
      }
      .name {
        font-size: 18px;
        color: black;
        margin-bottom: 10px;
      }
      .time {
        span {
          color: red;
        }
      }
      .price {
        color: red;
        font-size: 18px;
        position: absolute;
        right: 130px;
        bottom: 70px;
        margin: 0;
      }
      .btn {
        float: right;
        font-size: 18px;
        position: absolute;
        right: 30px;
        bottom: 60px;
        margin: 0;
      }
    }
  }
  .settlement {
    width: 782px;
    height: 50px;
    background-color: rgb(145, 148, 156);
    box-shadow: 1px 1px 2px 0 darkgray;
    position: absolute;
    bottom: -40px;

    .checkAll {
      float: left;
      color: black;
      margin: 15px 0 0 15px;
      span {
        color: black;
      }
    }
    p {
      float: right;
      margin: 13px 30px 0px 0;
    }
    .payBtn {
      width: 100px;
      height: 50px;
      float: right;
      border-radius: 0;
    }
  }
  .dialog1 {
    // text-align: center;
    .title {
      font-size: 20px;
      color: black;
      position: relative;
      bottom: 30px;
    }
    .text {
      font-size: 16px;
    }
  }
  .dialog2 {
    .text {
      color: black;
      font-size: 20px;
    }
    // div {
    //   // width: 300px;
    //   // height: 300px;
    //   // background-color: gray;
    //   // margin: 0 auto;
    //   // color: black;
    //   // font-size: 30px;
    //   // font-weight: bold;
    // }
  }
}
</style>